package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-ease/cache"
	"recruit-ease/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Recruit{}).Count(&count)

	var recruit []models.Recruit

	redis_key := "recruit_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Order("id DESC").Find(&recruit)
		jsonData, _ := json.Marshal(recruit)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &recruit)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": gin.H{
			"count": count,
			"data":  recruit,
		},
	})
}

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	var recruit models.Recruit
	models.DB.Where("id = ?", id).First(&recruit)

	redis_key := "recruit_detail" + strconv.Itoa(int(id))
	cache.Rdb.Set(cache.Ctx, redis_key, recruit, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": recruit,
	})

}

func CollectCount(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var recruit models.Recruit
	err := models.DB.Where("id = ?", id).First(&recruit)
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复收藏",
		})
		return
	}

	recruit.Collect++
	models.DB.Save(recruit)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return

}
